import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  private readonly logger = new Logger(HttpExceptionFilter.name);

  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const exceptionResponse = exception.getResponse();
    const errorMessage =
      typeof exceptionResponse === 'object' &&
      exceptionResponse !== null &&
      'message' in exceptionResponse
        ? (exceptionResponse as { message: string | string[] }).message
        : exception.message;

    // 记录错误日志
    this.logger.error(
      `${request.method} ${request.url} - ${status}: ${JSON.stringify(
        errorMessage,
      )}`,
    );

    // 格式化错误消息
    const message = Array.isArray(errorMessage)
      ? errorMessage[0]
      : errorMessage.toString();

    // 统一响应格式
    response.status(status).json({
      success: false,
      message,
      data: null,
    });
  }
}
